package sam.classe;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.net.ParseException;
import android.os.AsyncTask;
import android.util.Log;

public class ConnectDb extends AsyncTask<Object, Void, String> {

	private static final String LOGIN_URL_user = "http://samsam0246813579.livehost.fr/sam/?info=user";
	
	private String reponse;
	
	@Override
	protected String doInBackground(Object... params) {
		Log.d("Connexion", "Connect Button Pressed !");
		try{
			// get httpclient object and link to the target website
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(LOGIN_URL_user);
			// Build Parameters from the GUI data
			ArrayList<NameValuePair> queryParams = new ArrayList<NameValuePair>();
			queryParams.add(new BasicNameValuePair("username", params[0].toString()));
			queryParams.add(new BasicNameValuePair("password", params[1].toString()));
			// create and launch the POST request
			try
			{
				httppost.setEntity(new UrlEncodedFormEntity(queryParams));
				HttpResponse response = httpclient.execute(httppost);

				//Log.d("request!3", ));
				// decode received data
				this.reponse = EntityUtils.toString(response.getEntity());
			}catch(UnsupportedEncodingException e)
			{
				Log.e("e", e.toString());
			}catch(ParseException e)
			{
				Log.e("e", e.toString());
				
			}
		}catch(ClientProtocolException e)
		{
			Log.e("e", e.toString());
		}catch(IOException e)
		{
			Log.e("e", e.toString());
		}
		return null;
	}
	
	protected void onPostExecute(String result)
	{
		Connection.verif(this.reponse);
	}
	
}
